package com.xdh.springcloud.security.jwt.auth.ajax;

import com.xdh.springcloud.security.jwt.common.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

@Component
public class AjaxAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.notNull(authentication, "No authentication data provided");

        String userId = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

//        User user = userService.getByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

        if (!passwordEncoder.matches(password, "$e0801$AvWVxfGeD4EkdvK08Z8EMkYmlhVKsTZBXyC1l7SztdU8OPnEXrIbBdRsTO+wAPvQkIubRUY3wLoOdJd0+rFWog==$0LPuxlB83BE26qaODEwN7Tnhqn8GUKkgr/NYPNlQeXs=")) {
            throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
        }
        UserModel userModel = new UserModel("111111111111111111", "test");
        List<GrantedAuthority> authorities = new ArrayList<>();
        return new UsernamePasswordAuthenticationToken(userModel, null, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
